package com.plat.service.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.plat.dao.IBaseDao;
import com.plat.security.dao.SysRolesDao;
import com.plat.security.entity.SysRoles;
import com.plat.security.entity.SysRolesAuthorities;
import com.plat.service.ISysRoles;
import com.plat.service.ISysRolesAuthorities;

@Service
public class SysRolesImpl extends BaseServiceImpl<SysRoles> implements ISysRoles {

    @Autowired
    private SysRolesDao dao;

    @Autowired
    private ISysRolesAuthorities authoritService;

    @Override
    public IBaseDao<SysRoles> getDao() {
        return dao;
    }

    @Override
    public void updateMerge(Object o) {
        SysRoles roles = (SysRoles) o;

        if (StringUtils.isNotEmpty(roles.getAuthorityIds())) {
            String[] ids = roles.getAuthorityIds().split(",");

            List<SysRolesAuthorities> authorits = authoritService.findBy("roleId", roles.getRoleId());
            for (SysRolesAuthorities r : authorits) {
                authoritService.remove(r);
            }

            SysRolesAuthorities author = null;
            
            for (String id : ids) {
                author = new SysRolesAuthorities();
                author.setRoleId(roles.getRoleId());
                author.setAuthorityId(id);
                author.setEnabled(true);
                authoritService.save(author);
            }
            
        }
        super.updateMerge(o);
    }
}
